﻿/*
 * @author: wizardc
 */

using System.Reflection;
using Dou.UI;
using DouEditor.Utils;
using UnityEditor;
using UnityEngine;

namespace DouEditor.UI
{
    [CustomEditor(typeof(UISortingOrderController), true)]
    public class UISortingOrderControllerEditor : Editor
    {
        private UISortingOrderController _target;

        private void OnEnable()
        {
            _target = (UISortingOrderController) target;

            ForceRefresh();
        }

        private void ForceRefresh()
        {
            var children = _target.GetComponentsInChildren<UISortingOrderController>(true);
            foreach (var child in children)
            {
                child.ForceRefresh();
            }
        }

        public override void OnInspectorGUI()
        {
            var controlMode = _target.controlMode;
            var isRoot = _target.isRoot;
            
            if (_target.parent == null)
            {
                EditorUtil.DrawNonPublicField(_target, "_isRoot");
            }
            
            if (!isRoot)
            {
                EditorUtil.DrawNonPublicField(_target, "_parent");
            }

            EditorUtil.DrawNonPublicField(_target, "_localOrder");
            EditorUtil.DrawNonPublicField(_target, "order", false);
            EditorUtil.DrawNonPublicField(_target, "_controlMode");
            
            EditorGUI.BeginDisabledGroup(Application.isPlaying);
            EditorGUI.BeginChangeCheck();
            
            serializedObject.Update();
            
            if ((controlMode & UISortingOrderController.Mode.Canvas) > UISortingOrderController.Mode.None)
            {
                EditorGUILayout.PropertyField(serializedObject.FindProperty("_targetCanvas"));
            }
            
            if ((controlMode & UISortingOrderController.Mode.Renderer) > UISortingOrderController.Mode.None || 
                (controlMode & UISortingOrderController.Mode.DynamicRenderer) > UISortingOrderController.Mode.None)
            {
                EditorGUILayout.PropertyField(serializedObject.FindProperty("_targetRenderers"), true);
            }
            
            if (EditorGUI.EndChangeCheck())
            {
                serializedObject.ApplyModifiedProperties();
            }
            
            EditorGUI.EndDisabledGroup();
        }
        
        [MenuItem("CONTEXT/UISortingOrderController/缓存控制目标")]
        private static void CacheTargets(MenuCommand cmd)
        {
            var context = cmd.context as UISortingOrderController;
            if (context == null)
            {
                return;
            }

            Undo.RecordObject(context, "CacheTargets");
            EditorUtility.SetDirty(context);
            var invokeAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
            context.GetType().InvokeMember("CacheTargets", invokeAttr, null, context, null);
        }
    }
}
